package com.mzm.remoting.invoker;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;

public class Authenticator {
	private static final Logger logger = LoggerFactory.getLogger(Authenticator.class);
	private SecurityContextImpl securityContext;

	
	private void initContext() {
		securityContext = new SecurityContextImpl();
		InputStream loginProps = new ByteArrayInputStream("".getBytes());//Config.getValireResource("resources/login.properties");
//		if (loginProps == null) {
//			throw new IllegalStateException("No login.properties in $VALIRE_HOME/resources/");
//		}
		Properties properties = new Properties();
		try {
			properties.load(loginProps);
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
		String user = (String) properties.get("client.user");
		String pass = (String) properties.get("client.pass");
//		if (user == null || pass == null) {
//			throw new IllegalStateException(
//					"login.properties does not specify 'client.user' and 'client.pass'");
//		}
		
		logger.info("user = {}", user);
		
		/** The AUTHORITIES. */
		final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();

		AUTHORITIES.add(new GrantedAuthorityImpl("SYSTEM"));

		AUTHORITIES.add(new GrantedAuthorityImpl("ADMINISTRATOR"));
		
		UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, pass, AUTHORITIES);
		
		securityContext.setAuthentication(auth);

		/** The admin. */
		Authentication authenticatedUser = null;
		
		authenticatedUser = new UsernamePasswordAuthenticationToken(user, user, AUTHORITIES);

		SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
		
	}

	public void authenticateUsingConfiguration() {
		if (securityContext == null) {
			initContext();
		}
		SecurityContextHolder.setContext(securityContext);
	}

}
